package com.android.vgongyi.activity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;

import com.android.vgongyi.R;
import com.android.vgongyi.entity.WaterFallEntity;
import com.android.vgongyi.service.VGongyiService;
import com.android.vgongyi.utils.StringUtil;
import com.android.vgongyi.view.WaterFallView;
import com.android.vgongyi.view.WaterFallView.OnScrollListener;
import com.android.vgongyi.view.WaterTag;
import com.android.vgongyi.view.WaterView;

public class WaterFallActivity extends Activity {
	private static final String TAG = "WaterFallActivity";
	private final int column_count = 2;// 瀑布流的列数
	private final int page_count = 15;// 每页图片数

	private int loaded_count = 0;// 已加载数量
	private int current_page = 0;// 当前页数
	private int item_width;
	private int range;
	private int scroll_height;

	private int[] topIndex;
	private int[] bottomIndex;
	private int[] lineIndex;
	private int[] column_height;// 每列的高度
	private HashMap<Integer, Integer>[] pin_mark = null;
	private HashMap<Integer, String> pins;
	private HashMap<Integer, WeakReference<WaterView>> iviews;
	private ArrayList<LinearLayout> waterfall_items;
	private ArrayList<WaterFallEntity> waterFallEntityList;
	private Handler handler;
	private Display display;
	private WaterFallView waterfall_scroll;
	private LinearLayout waterfall_container;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		System.out.println("onCreate");
		setContentView(R.layout.activity_waterfall);
		waterFallEntityList = new ArrayList<WaterFallEntity>();
		new LoadWaterFallData().execute("1", "");

		display = this.getWindowManager().getDefaultDisplay();
		item_width = display.getWidth() / column_count;

		column_height = new int[column_count];
		iviews = new HashMap<Integer, WeakReference<WaterView>>();
		pins = new HashMap<Integer, String>();
		pin_mark = new HashMap[column_count];

		this.lineIndex = new int[column_count];
		this.bottomIndex = new int[column_count];
		this.topIndex = new int[column_count];

		for (int i = 0; i < column_count; i++) {
			lineIndex[i] = -1;
			bottomIndex[i] = -1;
			pin_mark[i] = new HashMap();
		}

		InitLayout();
	}

	private void InitLayout() {
		waterfall_scroll = (WaterFallView) findViewById(R.id.waterfall_scroll);
		range = waterfall_scroll.computeVerticalScrollRange();

		waterfall_scroll.getView();
		waterfall_scroll.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onTop() {
				// 滚动到最顶端
			}

			@Override
			public void onScroll() {
			}

			@Override
			public void onBottom() {
				try{
					// 滚动到最低端
					Log.i(TAG, "load data");
					System.out.println("threadcount----->" + WaterView.threadCount);
					if (WaterView.threadCount < 15) {
						new LoadWaterFallData().execute("1", waterFallEntityList.get(waterFallEntityList.size() - 1).getId());
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onAutoScroll(int l, int t, int oldl, int oldt) {
				try{
				Log.d(TAG,String.format("%d  %d  %d  %d", l, t, oldl, oldt));
				Log.d(TAG, "range:" + range);
				Log.d(TAG, "range-t:" + (range - t));
				scroll_height = waterfall_scroll.getMeasuredHeight();
				Log.d(TAG, "scroll_height:" + scroll_height);
				if (t > oldt) {// 向下滚动
					if (t > 2 * scroll_height) {// 超过两屏幕后
						for (int k = 0; k < column_count; k++) {
							LinearLayout localLinearLayout = waterfall_items.get(k);
							if (pin_mark[k].get(Math.min(bottomIndex[k] + 1,lineIndex[k])) <= t + 3 * scroll_height) {// 最底部的图片位置小于当前t+3*屏幕高度
								((WaterView) waterfall_items.get(k).getChildAt(Math.min(1 + bottomIndex[k],lineIndex[k]))).Reload();
								bottomIndex[k] = Math.min(1 + bottomIndex[k],lineIndex[k]);
							}
							Log.d(TAG,"headIndex:" + topIndex[k] + "  footIndex:"+ bottomIndex[k] + "  headHeight:"+ pin_mark[k].get(topIndex[k]));
							if (pin_mark[k].get(topIndex[k]) < t - 2 * scroll_height) {// 未回收图片的最高位置<t-两倍屏幕高度
								int i1 = topIndex[k];
								topIndex[k]++;
								((WaterView) localLinearLayout.getChildAt(i1)).recycle();
								Log.d(TAG, "recycle,k:" + k + " headindex:"+ topIndex[k]);
							}
						}
					}
				} else {// 向上滚动
					if (t > 2 * scroll_height) {// 超过两屏幕后
						for (int k = 0; k < column_count; k++) {
							LinearLayout localLinearLayout = waterfall_items.get(k);
							if (pin_mark[k].get(bottomIndex[k]) > t + 3* scroll_height) {
								((WaterView) localLinearLayout.getChildAt(bottomIndex[k])).recycle();
								bottomIndex[k]--;
							}

							if (pin_mark[k].get(Math.max(topIndex[k] - 1, 0)) >= t- 2 * scroll_height) {
								((WaterView) localLinearLayout.getChildAt(Math.max(-1 + topIndex[k], 0))).Reload();
								topIndex[k] = Math.max(topIndex[k] - 1, 0);
							}
						}
					}
				}
				}catch(Exception e){
					e.printStackTrace();
				}

			}
		});

		waterfall_container = (LinearLayout) this
				.findViewById(R.id.waterfall_container);
		handler = new Handler() {

			@Override
			public void dispatchMessage(Message msg) {

				super.dispatchMessage(msg);
			}

			@Override
			public void handleMessage(Message msg) {

				// super.handleMessage(msg);

				switch (msg.what) {
				case 1:

					WaterView v = (WaterView) msg.obj;
					int w = msg.arg1;
					int h = msg.arg2;
					Log.d(TAG,String.format("获取实际View高度:%d,ID：%d,columnIndex:%d,rowIndex:%d,filename:%s",v.getHeight(), v.getId(), v.getColumnIndex(), v.getRowIndex(),v.getFlowTag().getFileName()));
					String f = v.getFlowTag().getFileName();
					// 此处计算列值
					int columnIndex = GetMinValue(column_height);
					v.setColumnIndex(columnIndex);
					column_height[columnIndex] += h;
					pins.put(v.getId(), f);
					iviews.put(v.getId(), new WeakReference<WaterView>(v));
					waterfall_items.get(columnIndex).addView(v);
					lineIndex[columnIndex]++;
					pin_mark[columnIndex].put(lineIndex[columnIndex],column_height[columnIndex]);
					bottomIndex[columnIndex] = lineIndex[columnIndex];
					break;
				}
			}

			@Override
			public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
				return super.sendMessageAtTime(msg, uptimeMillis);
			}
		};

		waterfall_items = new ArrayList<LinearLayout>();
		for (int i = 0; i < column_count; i++) {
			LinearLayout itemLayout = new LinearLayout(this);
			LinearLayout.LayoutParams itemParam = new LinearLayout.LayoutParams(item_width, LayoutParams.WRAP_CONTENT);
			itemLayout.setPadding(2, 2, 2, 2);
			itemLayout.setOrientation(LinearLayout.VERTICAL);
			itemLayout.setLayoutParams(itemParam);
			waterfall_items.add(itemLayout);
			waterfall_container.addView(itemLayout);
		}
	}

	private void AddItemToContainer(int pageindex, int pagecount) {
		int currentIndex = pageindex * pagecount;
		int imagecount = waterFallEntityList.size();
		System.out.println("imagecount-->" + imagecount);
		System.out.println("currentIndex-->" + currentIndex);
		for (int i = currentIndex; i < pagecount * (pageindex + 1)
				&& i < imagecount; i++) {
			loaded_count++;
			Random rand = new Random();
			int r = rand.nextInt(imagecount);
			AddImage(StringUtil.namePicture(waterFallEntityList.get(r).getImg_url(), waterFallEntityList.get(r).getImg_extension()), (int) Math.ceil(loaded_count/ (double) column_count), loaded_count - 1);
		}

	}

	private void AddImage(String fileName, int rowIndex, int id) {
		System.out.println("addimage--->" + id);
		WaterView item = new WaterView(this);
		item.setRowIndex(rowIndex);
		item.setId(id);
		item.setViewHandler(this.handler);
		WaterTag param = new WaterTag();
		param.setWaterId(id);
		param.setFileName(fileName);
		param.setItemWidth(item_width);
		param.setId(waterFallEntityList.get(id).getId());
		param.setImg_id(waterFallEntityList.get(id).getImg_id());
		param.setImg_url(waterFallEntityList.get(id).getImg_url());
		param.setImg_extension(waterFallEntityList.get(id).getImg_extension());
		param.setInsert_date(waterFallEntityList.get(id).getInsert_date());
		param.setBig_height(waterFallEntityList.get(id).getBig_height());
		param.setBig_width(waterFallEntityList.get(id).getBig_width());
		item.setFlowTag(param);
		item.LoadImage();
		item.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
				intent.putExtra("data",waterFallEntityList.get(loaded_count - 1).getId());
				setResult(Activity.RESULT_OK,intent);
				WaterFallActivity.this.finish();
			}
		});
	}

	private int GetMinValue(int[] array) {
		int m = 0;
		int length = array.length;
		for (int i = 0; i < length; ++i) {
			if (array[i] < array[m]) {
				m = i;
			}
		}
		return m;
	}

	private class LoadWaterFallData extends AsyncTask<String, String, String> {
		private ArrayList<WaterFallEntity> list;

		public LoadWaterFallData(){
			list = new ArrayList<WaterFallEntity>();
		}
		@Override
		protected String doInBackground(String... params) {
			list = new VGongyiService(getApplicationContext()).getWaterFallList(params[0], params[1]);
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			try{
				waterFallEntityList.addAll(list);
				AddItemToContainer(current_page++, page_count);
			}catch(Exception e){
				e.printStackTrace();
			}	
			super.onPostExecute(result);
		}

	}
}
